package gdt.service;


import java.util.List;

import javax.persistence.NoResultException;

import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import gdt.dao.GroupDAO;
import gdt.entity.Group;
import gdt.entity.Member;
import gdt.service.utils.FileUpload;
import gdt.service.utils.Validator;

public class GroupService {

	@Transactional(readOnly=true)
	public Group find(String username){
		Member user = (Member) userDetailsService.loadUserByUsername(username);
		
		return user.getGroup();
	}
	
	public Group findByName(String name){
		return groupDao.findByName(name);
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public void save(Group group){
		group = groupDao.makePersistent(group);
	}
	
	@Transactional(readOnly=true)
	public List<Group> getGroups(){
		return groupDao.findAll();
	}
	
	public Group setup(){
		return new Group();
	}
	
	public FileUpload getImageFileUpload(Group group){
		FileUpload fileUpload = new FileUpload();
		fileUpload.setGroup(group);
		return fileUpload;
	}
	
	
	/********************************* DAO's *********************************/
	
	private GroupDAO groupDao;

	public void setGroupDao(GroupDAO groupDao) {
		this.groupDao = groupDao;
	}
	
	private UserDetailsService userDetailsService;

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}
	
	
	/******************************* Validation *******************************/
	
	private Validator validator;
	
	public boolean validate(Group group, MessageContext context){
		boolean valid = validator.validate(group, context);
		
		Group groupWithName = null;
		try{
			groupWithName = findByName(group.getName());
		}catch(NoResultException e){
			//The group name isn't registered yet, so we just do nothing
		}

		if((groupWithName != null) && ((group.getId() == 0) || (groupWithName.getId() != group.getId()))){
			context.addMessage((new MessageBuilder()).error().code("error_existing_groupname").build());
			valid = false;
		}
			
		return valid;
	}
	
	public Validator getValidator() {
		return validator;
	}

	public void setValidator(Validator validator) {
		this.validator = validator;
	}
}
